import requests
from log.log import test_log

def request_run_main(url=None, header=None, data=None, method="post"):
    # 记录日志
    test_log.info(f'请求开始: 请求url: {url}, 请求数据: {data}，请求头: {header}')
    
    try:
        # 检查header是否为空
        if not header:
            raise ValueError("请求头不能为空")
        
        method = method.lower()  # 将method参数转换为小写
        header = {k.lower(): v for k, v in header.items()}  # 将header中的所有键转为小写

        if method == 'get':
            response = requests.get(url=url, headers=header, params=data)  # 使用params传递查询参数
        
        elif method == 'post':
            if header.get("content-type") == "application/json":
                response = requests.post(url=url, headers=header, json=data)
            elif header.get("content-type") == 'application/x-www-form-urlencoded':
                response = requests.post(url=url, headers=header, data=data)
            else:
                raise ValueError(f"Unsupported Content-Type: {header['content-type']}")
        
        else:
            raise ValueError(f"Unsupported HTTP method: {method}")
        
        # 捕获响应的json解析异常
        try:
            response_data = response.json()
        except ValueError:
            test_log.error(f"无法解析JSON响应: {response.text}")
            response_data = {}

        test_log.info(f"响应数据: {response_data}")
        return response
    
    except requests.RequestException as e:
        test_log.error(f"HTTP request failed: {e}") 
        return None
    except ValueError as e:
        test_log.error(f"ValueError: {e}")
        return None
